package edu.cuit.copilot.config;

import edu.cuit.copilot.listener.RedisMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, ?> redisTemplate(RedisConnectionFactory factory){
        var template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        //指定key的序列化器
        template.setKeySerializer(RedisSerializer.string());
        //设置value的序列化器(采用的java的序列化机制)
        //template.setValueSerializer(RedisSerializer.java());
        template.setValueSerializer(RedisSerializer.json());
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory factory, @Autowired RedisMessageListener listener){
        var container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        //只有线程池生存，才会继续监听
        var executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(3);

        container.setTaskExecutor(executor);

        var map = new HashMap<MessageListener, Collection<? extends Topic>>();
        map.put(listener, List.of(new ChannelTopic("chat")));
        container.setMessageListeners(map);
        return container;
    }
}
